import i18n from '@app-base/common/utils/i18next';
import { nmAppErrorLog, nmAppLog } from '@app-nextmesh/common/utils';
import {
  CommandDialog2,
  CommandDialog2Footer,
} from '@app-nextmesh/components/Dialogs';
import { documentV2 } from '@app-nextmesh/domain';
import { useProjectStore } from '@app-nextmesh/store/project';
import { useTasksStore } from '@app-nextmesh/store/tasks';
import {
  IMeshBoundaryLayer,
  IMeshDistribution,
  IMeshSize,
  ITask,
  NMMeshBaseCommand,
} from '@app-nextmesh/types';
import { NMMeshCtrlCmdDialogParams } from '@app-nextmesh/types/command';
import { RJSFSchema, UiSchema } from '@rjsf/utils';
import { Button } from 'antd';
import _, { isArray } from 'lodash';
import { useEffect, useState } from 'react';
import { SelectedEntitiesSchema3, SizeSchema } from '../jsonSchema';

export default function CmdAutoMeshDialog({
  title,
  onClose,
  pickTypes,
  isGlobal,
  schema,
}: NMMeshCtrlCmdDialogParams<{
  id: string;
  formData: IMeshBoundaryLayer | IMeshDistribution | IMeshSize;
}>) {
  const controlType = 'MeshSize';
  const { projectInfo, setProjectInfo } = useProjectStore((state) => state);
  const { tasks } = useTasksStore();
  const [meshStatus, setMeshStatus] = useState<ITask['status']>(null);
  const [formData, setFormData] = useState<
    IMeshBoundaryLayer | IMeshDistribution | IMeshSize
  >(null);

  useEffect(() => {
    const meshControl = projectInfo?.meshControl?.params;
    if (meshControl) {
      const meshSize = meshControl[controlType];
      const globalIndex = meshSize?.findIndex((value) => value.isGlobal);
      if (globalIndex >= 0) {
        setFormData(meshSize[globalIndex]);
      }
    }
  }, [projectInfo, controlType]);
  /**
   * 检查任务状态
   */
  useEffect(() => {
    const uuid = 'mesh';
    nmAppLog('autoMesh check tasks', {
      uuid,
      tasks,
    });
    if (!isArray(tasks)) {
      return;
    }
    const task = tasks.find((task) => task?.uuid === uuid);
    if (task) {
      setMeshStatus(task.status);
    }
  }, [tasks]);
  const uiSchema: UiSchema = {
    SelectedEntities: {
      'ui:field': 'entity',
      pickTypes: pickTypes,
      'ui:options': {
        visible: !isGlobal,
      },
    },
  };
  const onSubmit = async (data) => {
    if (!data) {
      return;
    }
    let meshControl = projectInfo.meshControl;
    if (!meshControl) {
      meshControl = {
        params: {
          MeshSize: [],
          Distribution: [],
          BoundaryLayer: [],
        },
      };
    }
    if (!meshControl.params) {
      meshControl.params = {
        MeshSize: [],
        Distribution: [],
        BoundaryLayer: [],
      };
    }

    if (isGlobal) {
      // 全局的没有formIndex，通过isGlobal来判断存储的数据是否存在
      data.isGlobal = true;
      data.SelectedEntities = [];
      // 删除已有的全局数据，重新添加
      _.remove(meshControl.params[controlType], (value) => value.isGlobal);
      // 用循环存在闭包问题，所以直接赋值
      const newGlobal = [
        {
          ...data,
          MeshingDim: 1,
        },
        {
          ...data,
          MeshingDim: 2,
        },
        {
          ...data,
          MeshingDim: 3,
        },
      ];
      meshControl.params[controlType].push(...newGlobal);
    }
    projectInfo.meshControl = meshControl;
    try {
      await documentV2.updateMeshControl(projectInfo.meshControl);
      setProjectInfo({ ...projectInfo });
      await documentV2.autoMesh();
      setMeshStatus('STARTED');
    } catch (error) {
      nmAppErrorLog('CmdControl', 'onSubmit', error);
    }
  };
  let buttonTitle = title;
  let buttonEnable = true;
  switch (meshStatus) {
    case 'STARTED':
      buttonTitle = i18n.t('command.mesh.meshing');
      buttonEnable = false;
      break;
    case 'CANCELING':
      buttonTitle = i18n.t('canceling');
      buttonEnable = false;
      break;
    case 'FAILED':
      buttonTitle = i18n.t('tips.failed');
      break;
  }
  return (
    <CommandDialog2
      title={title}
      formData={formData}
      schema={schema}
      extraUiSchema={uiSchema}
      onClose={onClose}
      onSubmit={onSubmit}
      disabled={meshStatus === 'STARTED'}>
      <CommandDialog2Footer>
        <Button
          disabled={!buttonEnable}
          type='primary'
          danger={meshStatus === 'STARTED'}
          htmlType='submit'>
          {buttonTitle}
        </Button>
      </CommandDialog2Footer>
    </CommandDialog2>
  );
}

const schema: RJSFSchema = {
  type: 'object',
  properties: {
    ...SizeSchema,
    ...SelectedEntitiesSchema3,
  },
};
export const cmdAutoMesh: NMMeshBaseCommand = {
  id: 'cmdAutoMesh',
  label: 'command.mesh.auto',
  icon: 'commands/simu/generate-mesh',
  create: (label, onClose, _, customParams) => (
    <CmdAutoMeshDialog
      title={i18n.t(label)}
      onClose={onClose}
      params={customParams}
      pickTypes={[]}
      isGlobal
      schema={schema}
    />
  ),
};
